package com.jt.base;

import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

public abstract class BaseService<K, T> {

    @Autowired
    protected Mapper<T> mapper;

    public Mapper<T> getMapper() {
        return mapper;
    }

    /**
     * 根据key查对象
     * @param key
     * @return
     */
    public T selectByKey(K key) {
        return mapper.selectByPrimaryKey(key);
    }

    /**
     * 添加对象
     * @param entity
     * @return
     */
    public T insert(T entity) {
        mapper.insert(entity);
        return entity;
    }

    /**
     * 删除对象
     * @param key
     * @return
     */
    public int delete(K key) {
        return mapper.deleteByPrimaryKey(key);
    }

    /**
     * 根据条件删除
     * @param example
     * @return
     */
    public int deleteByExample(Example example) {
        return mapper.deleteByExample(example);
    }

    /**
     * 删除想象
     * @param entity
     * @return
     */
    public int deleteByEntity(T entity) {
        return mapper.delete(entity);
    }

    /**
     * 更新新的model中所有的字段，未设值的属性会被更新null
     * @param entity
     * @return
     */
    public int update(T entity) {
        return mapper.updateByPrimaryKey(entity);
    }

    /**
     * 更新新的model中不为空的字段
     * @param entity
     * @return
     */
    public int updateNotNull(T entity) {
        return mapper.updateByPrimaryKeySelective(entity);
    }

    /**
     * 根据Example条件更新实体`entity`包含的全部属性，null值会被更新
     */
    public int updateByExample(T entity,  Example example) {
        return mapper.updateByExample(entity,example);
    }

    /**
     * 根据Example条件更新实体`entity`包含的不是null的属性值
     */
    public int updateNotNullByExample(T entity,  Example example) {
        return mapper.updateByExampleSelective(entity,example);
    }

    /**
     * 根据条件获取list
     * @param example
     * @return
     */
    public List<T> selectListByExample(Example example) {
        return mapper.selectByExample(example);
    }

    /**
     * 根据条件获取分页list
     * @param example
     * @return
     */
    public List<T> selectListByExample(Example example, int page, int rows) {
        PageHelper.startPage(page, rows);   //分页查询
        return mapper.selectByExample(example);
    }

    /**
     * 获取所有list
     * @return
     */
    public List<T> selectAll() {
        return mapper.selectAll();
    }

    public int count(T t){
       return mapper.selectCount(t);
    }

}
